import pyautogui
import time
import tkinter as tk
from PIL import ImageGrab


class ColorDetector:
    def __init__(self):
        # 初始化目标颜色列表（将提供的数字转换为RGB元组）
        self.target_colors = [self.int_to_rgb(n) for n in [
            341043710,
            345308926,
            340522485,
            336920575
        ]]

        # 创建GUI界面
        self.root = tk.Tk()
        self.root.title("智能颜色检测器")

        # 状态标签
        self.status = tk.Label(self.root, text="正在检测...", font=('Arial', 12))
        self.status.pack(pady=5)

        # 颜色显示框
        self.color_frame = tk.Frame(self.root, width=120, height=120,
                                    highlightthickness=2, highlightbackground="gray")
        self.color_frame.pack(pady=10)

        # 信息标签
        self.info = tk.Label(self.root, font=('Arial', 10))
        self.info.pack(pady=5)

    @staticmethod
    def int_to_rgb(n):
        """将整数转换为RGB元组"""
        return (
            (n >> 16) & 0xFF,  # 红色通道
            (n >> 8) & 0xFF,  # 绿色通道
            n & 0xFF  # 蓝色通道
        )

    def update_display(self, pixel, hex_color, x, y):
        """更新界面显示"""
        # 更新颜色框背景
        self.color_frame.config(bg=hex_color)

        # 更新坐标信息
        coord_info = f"坐标：({x}, {y})"
        color_info = f"RGB: {pixel}\nHEX: {hex_color}"

        # 检查颜色匹配
        if pixel in self.target_colors:
            self.status.config(text="✅ 匹配到目标颜色！", fg="green")
            self.color_frame.config(highlightbackground="green")
            match_info = "（目标颜色之一）"
        else:
            self.status.config(text="正在检测...", fg="black")
            self.color_frame.config(highlightbackground="gray")
            match_info = ""

        self.info.config(text=f"{coord_info}\n{color_info}{match_info}")

    def update_color(self):
        try:
            # 获取鼠标位置
            x, y = pyautogui.position()

            # 获取屏幕颜色（支持多显示器）
            screenshot = ImageGrab.grab()
            pixel = screenshot.getpixel((x, y))

            # 转换为HEX格式
            hex_color = '#{:02x}{:02x}{:02x}'.format(*pixel)

            # 更新界面
            self.update_display(pixel, hex_color, x, y)

            # 每50ms更新一次
            self.root.after(50, self.update_color)
        except Exception as e:
            print(f"检测错误: {e}")

    def run(self):
        self.root.after(0, self.update_color)
        self.root.mainloop()


if __name__ == "__main__":
    detector = ColorDetector()
    try:
        detector.run()
    except KeyboardInterrupt:
        print("程序已安全退出")